package com.sc.nft.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.mate.sdk.domain.Key;
import com.sc.nft.dao.*;
import com.sc.nft.entity.*;
import com.sc.nft.entity.dto.*;
import com.sc.nft.entity.vo.*;
import com.sc.nft.entity.vo.ecology.adminDaoPhoneVO;
import com.sc.nft.entity.vo.salvageEvents.PageDaoEcologyPointsTransferRecordsVO;
import com.sc.nft.enums.RedisKeyEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.helper.MetaChainHepler;
import com.sc.nft.pool.UserPool;
import com.sc.nft.service.CatenaCertificateService;
import com.sc.nft.service.MallIncomeService;
import com.sc.nft.service.UserCreatorInfoService;
import com.sc.nft.service.UserCreatorPhoneRecordService;
import com.sc.nft.sup.ErrorCode;
import com.sc.nft.sup.PageRequest;
import com.sc.nft.util.RedisUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 服务接口实现
 *
 * @author Sun
 * @description 由 Mybatisplus Code Generator 创建
 * @since 2022-05-30 15:17:11
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class UserCreatorInfoServiceImpl implements UserCreatorInfoService {

    private final UserCreatorInfoDao userCreatorInfoDao;

    private final UserInfoDao userInfoDao;

    private final StaticDataDao staticDataDao;

    private final UserCollectionDao userCollectionDao;

    private final CatenaCertificateService catenaCertificateService;
    private final DigitalCollectionDao digitalCollectionDao;
    private final DigitalCollectionProductInfoDao digitalCollectionProductInfoDao;
    private final DaoIdentityDao daoIdentityDao;


    private final MallIncomeService mallIncomeService;
    private final DaoGasDao daoGasDao;
    private final MetaChainHepler metaChainHepler;
    private final RedisUtil redisUtil;
    private final DaoEcologyPointsTransferRecordsDao daoEcologyPointsTransferRecordsDao;

    private final UserCreatorPhoneRecordService userCreatorPhoneRecordService;
    @Value("${enableRewardConsumption.daoId:33}")
    private String enableRewardConsumption;

    public List<String> getRewardConsumptionDaoIdList() {
        return Arrays.asList(enableRewardConsumption.split(","));
    }

    @Override
    public List<UserCreatorInfo> getUserCreator() {
        return userCreatorInfoDao.getUserCreator();
    }

    @Override
    public Page<UserCreatorInfo> pageUserCreator(int pageNo, int pageSize, String nickName) {
        return userCreatorInfoDao.pageUserCreator(pageNo, pageSize, nickName);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUserCreator(Long id, String nickName, String creatorPresentation, String creatorAvatarImg) {
        redisUtil.del(RedisKeyEnum.HOME_BRAND_ISLAND.getKey());
        return userCreatorInfoDao.updateUserCreator(id, nickName, creatorPresentation, creatorAvatarImg);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addUserCreator(String nickName, String creatorAvatarImg, String creatorPresentation) {
        UserCreatorInfo userCreatorInfo = new UserCreatorInfo();
        userCreatorInfo.setNickName(nickName);
        userCreatorInfo.setCreatorAvatarImg(creatorAvatarImg);
        userCreatorInfo.setCreatorPresentation(creatorPresentation);
        Boolean result = userCreatorInfo.insert();
        redisUtil.del(RedisKeyEnum.HOME_BRAND_ISLAND.getKey());
        return result;
    }

    @Override
    public Page<UserCreatorListVO> getUserCreatorList(int pageNo, int pageSize) {
        return userCreatorInfoDao.getUserCreatorList(pageNo, pageSize);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean userApplyCreatedDao(UserApplyCreatedDaoDTO userApplyCreatedDaoDTO) {
        StaticData imgHost = staticDataDao.getByType("imgHost");
        userApplyCreatedDaoDTO.setCreatorAvatarImg(imgHost.getValue() + userApplyCreatedDaoDTO.getCreatorAvatarImg());
        userApplyCreatedDaoDTO.setCreatorBackGroundImg(imgHost.getValue() + userApplyCreatedDaoDTO.getCreatorBackGroundImg());
        userApplyCreatedDaoDTO.setCreatorBackGroundImg2(imgHost.getValue() + userApplyCreatedDaoDTO.getCreatorBackGroundImg2());
        userApplyCreatedDaoDTO.setBrandStory(imgHost.getValue() + userApplyCreatedDaoDTO.getBrandStory());
        UserCreatorInfo userCreatorInfo = new UserCreatorInfo();
        BeanUtil.copyProperties(userApplyCreatedDaoDTO, userCreatorInfo);
        // 获取用户城主卡,获取的时候考虑用户有多张城主卡的情况,只获取ID最小的那一条.
        StaticData cityLordCollectionId = staticDataDao.getByType("city_lord_collection_id");
        // 城主卡的藏品id
        Long value = Convert.toLong(cityLordCollectionId.getValue());
        // 根据城主卡藏品id,获取用户藏品的对应数据.如果为空的话,则报错.如果不为空的话,获取的id最小的一条进行绑定到这个dao上.
        UserCollection userApplyCreatedDaoCastellanRights = userCollectionDao.getUserApplyCreatedDaoCastellanRights(value);
        if (BeanUtil.isEmpty(userApplyCreatedDaoCastellanRights)) {
            throw new GlobalRunTimeException("暂无申请权限");
        }
        userCreatorInfo.setUserId(UserPool.getUser().getId());
        userCreatorInfo.setUserCollectionId(userApplyCreatedDaoCastellanRights.getId());
        userCreatorInfo.setDaoUuid(UUID.fastUUID().toString().replaceAll("-", ""));
        userCreatorInfo.insert();
        DaoWallet wallet = new DaoWallet();
        wallet.setBalance(BigDecimal.ZERO);
        wallet.setFreezeAmount(BigDecimal.ZERO);
        wallet.setSumIncome(BigDecimal.ZERO);
        wallet.insert();
        MallDaoWallet mallDaoWallet = new MallDaoWallet();
        mallDaoWallet.setDaoId(userCreatorInfo.getId());
        mallDaoWallet.setBalance(BigDecimal.ZERO);
        mallDaoWallet.setActivityBalance(BigDecimal.ZERO);
        mallDaoWallet.setFreezeAmount(BigDecimal.ZERO);
        mallDaoWallet.setSumIncome(BigDecimal.ZERO);
        mallDaoWallet.insert();
        redisUtil.del(RedisKeyEnum.HOME_BRAND_ISLAND.getKey());
        return Boolean.TRUE;
    }

    /**
     * 获取我自己创建的dao列表
     *
     * @return
     */
    @Override
    public Page<GetUserApplyCreateDaoVO> getUserApplyCreateDaoVO(PageRequest pageRequest) {
        return userCreatorInfoDao.getUserApplyCreateDaoVO(pageRequest);
    }

    @Override
    public Page<GetUserApplyCreateDaoVO> userJoinGroup(PageRequest pageRequest) {
        Page<GetUserApplyCreateDaoVO> userApplyCreateDaoVO = userCreatorInfoDao.userJoinGroup(pageRequest);
        if (pageRequest.getPageNo().equals(1)) {
            GetUserApplyCreateDaoVO certainlyShowData = userCreatorInfoDao.getCertainlyShowData();
            if (!CollUtil.isEmpty(userApplyCreateDaoVO.getRecords())) {
                userApplyCreateDaoVO.getRecords().remove(certainlyShowData);
                userApplyCreateDaoVO.getRecords().add(0, certainlyShowData);
            } else {
                List<GetUserApplyCreateDaoVO> list = new ArrayList<>();
                list.add(certainlyShowData);
                userApplyCreateDaoVO.setRecords(list);
            }
        }
        return userApplyCreateDaoVO;
    }

    @Override
    public List<HomeBrandIslandVO> homeBrandIsland() {
        Object object = redisUtil.get(RedisKeyEnum.HOME_BRAND_ISLAND.getKey());
        if (ObjectUtil.isNotEmpty(object)) {
            List<HomeBrandIslandVO> data = Lists.newArrayList();
            List list = JSONObject.parseArray(object.toString());
            list.forEach(r -> {
                        HomeBrandIslandVO homeBrandIslandVO = JSONObject.parseObject(r.toString(), HomeBrandIslandVO.class);
                        data.add(homeBrandIslandVO);
                    }
            );
            return data;
        } else {
            List<HomeBrandIslandVO> data = userCreatorInfoDao.homeBrandIsland();
            if (CollUtil.isEmpty(data)) {
                return data;
            }
            // 把品牌岛的id获取出来,查询用户的关注数量
            List<Long> dataIds = data.stream().map(HomeBrandIslandVO::getId).collect(Collectors.toList());
            List<CatenaIdsGroupByCatenaVO> catenaIdsGroupByCatena = catenaCertificateService.selectByCatenaIdsGroupByCatena(dataIds);
            data.forEach(homeBrandIslandVO -> {
                Long id = homeBrandIslandVO.getId();
                List<CatenaIdsGroupByCatenaVO> collect = catenaIdsGroupByCatena.stream().filter(catenaIdsGroupByCatenaVO -> catenaIdsGroupByCatenaVO.getCatenaId().equals(id)).collect(Collectors.toList());
                if (CollUtil.isEmpty(collect)) {
                    return;
                }
                CatenaIdsGroupByCatenaVO catenaIdsGroupByCatenaVO = collect.get(0);
                homeBrandIslandVO.setFansSum(homeBrandIslandVO.getFansSum() + catenaIdsGroupByCatenaVO.getSum());
            });
            String stringData = JSONObject.toJSON(data).toString();
            redisUtil.set(RedisKeyEnum.HOME_BRAND_ISLAND.getKey(), stringData, 30);

            return data;
        }
    }

    /**
     * 品牌岛全部带分页
     *
     * @param request
     * @return
     */
    @Override
    public Page<HomeBrandIslandVO> homeBrandIslandPage(HomeBrandIslandDTO request) {
        Page<HomeBrandIslandVO> data = userCreatorInfoDao.homeBrandIslandPage(request);
        if (CollUtil.isEmpty(data.getRecords())) {
            return data;
        }
        // 把品牌岛的id获取出来,查询用户的关注数量
        List<Long> dataIds = data.getRecords().stream().map(HomeBrandIslandVO::getId).collect(Collectors.toList());
        List<CatenaIdsGroupByCatenaVO> catenaIdsGroupByCatena = catenaCertificateService.selectByCatenaIdsGroupByCatena(dataIds);
        data.getRecords().forEach(homeBrandIslandVO -> {
            homeBrandIslandVO.setStarRating(StrUtil.isNotBlank(homeBrandIslandVO.getStarRating()) ? new BigDecimal(homeBrandIslandVO.getStarRating()).setScale(1, BigDecimal.ROUND_DOWN).toPlainString() : "0.0");
            Long id = homeBrandIslandVO.getId();
            List<CatenaIdsGroupByCatenaVO> collect = catenaIdsGroupByCatena.stream().filter(catenaIdsGroupByCatenaVO -> catenaIdsGroupByCatenaVO.getCatenaId().equals(id)).collect(Collectors.toList());
            if (CollUtil.isEmpty(collect)) {
                return;
            }
            CatenaIdsGroupByCatenaVO catenaIdsGroupByCatenaVO = collect.get(0);
            homeBrandIslandVO.setFansSum(homeBrandIslandVO.getFansSum() + catenaIdsGroupByCatenaVO.getSum());
        });
        return data;
    }

    @Override
    public GetDaoByIdVO getDaoById(Long id) {
        if (id == null) {
            throw new GlobalRunTimeException("参数异常");
        }
        GetDaoByIdVO daoById = userCreatorInfoDao.getDaoById(id);
        if (BeanUtil.isEmpty(daoById)) {
            throw new GlobalRunTimeException("该Dao不存在");
        }
        daoById.setStarRating(StrUtil.isNotBlank(daoById.getStarRating()) ? new BigDecimal(daoById.getStarRating()).setScale(1, BigDecimal.ROUND_DOWN).toPlainString() : "0.0");
        List<Long> ids = new ArrayList<>();
        ids.add(daoById.getId());
        List<CatenaIdsGroupByCatenaVO> catenaIdsGroupByCatena = catenaCertificateService.selectByCatenaIdsGroupByCatena(ids);
        if (!CollUtil.isEmpty(catenaIdsGroupByCatena)) {
            daoById.setFansSum(daoById.getFansSum() + catenaIdsGroupByCatena.get(0).getSum());
        }
        if (this.getRewardConsumptionDaoIdList().contains(String.valueOf(id))) {
            daoById.setEnableRewardConsumption(true);
        }
        return daoById;
    }

    @Override
    public Map<Long, UserCreatorInfo> getDaoByIdsToMap(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return new HashMap<>();
        }
        List<UserCreatorInfo> daoByIds = userCreatorInfoDao.getDaoByIds(ids);
        if (CollectionUtils.isEmpty(daoByIds)) {
            return new HashMap<>();
        }
        return daoByIds.stream().collect(Collectors.toMap(UserCreatorInfo::getId, x -> x));
    }

    @Override
    public GetDaoByIdVO getCertainlyShowDao() {
        GetDaoByIdVO certainlyShowDao = userCreatorInfoDao.getCertainlyShowDao();
        if (BeanUtil.isEmpty(certainlyShowDao)) {
            throw new GlobalRunTimeException("当前模块暂未开放");
        }
        List<Long> ids = new ArrayList<>();
        ids.add(certainlyShowDao.getId());
        List<CatenaIdsGroupByCatenaVO> catenaIdsGroupByCatena = catenaCertificateService.selectByCatenaIdsGroupByCatena(ids);
        if (!CollUtil.isEmpty(catenaIdsGroupByCatena)) {
            certainlyShowDao.setFansSum(certainlyShowDao.getFansSum() + catenaIdsGroupByCatena.get(0).getSum());
        }
        return certainlyShowDao;
    }

    /**
     * 后台管理获取dao列表
     *
     * @param adminPageListDTO
     * @return
     */
    @Override
    public Page<AdminUserCreatorInfoVO> getAdminPageList(AdminPageListDTO adminPageListDTO) {
        return userCreatorInfoDao.getAdminPageList(adminPageListDTO);
    }

    @Override
    public List<AdminUserCreatorInfoAllDao> getAll() {
        return userCreatorInfoDao.getAll();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void adminInsert(AddBrandVO addBrandVO) {
        UserCreatorInfo userCreatorInfo = new UserCreatorInfo();
        BeanUtil.copyProperties(addBrandVO, userCreatorInfo);
        userCreatorInfo.setDaoUuid(UUID.fastUUID().toString().replaceAll("-", ""));
        userCreatorInfo.insert();
        DaoWallet wallet = new DaoWallet();
        wallet.setDaoId(userCreatorInfo.getId());
        wallet.setBalance(BigDecimal.ZERO);
        wallet.setFreezeAmount(BigDecimal.ZERO);
        wallet.setSumIncome(BigDecimal.ZERO);
        wallet.insert();
        MallDaoWallet mallDaoWallet = new MallDaoWallet();
        mallDaoWallet.setDaoId(userCreatorInfo.getId());
        mallDaoWallet.setBalance(BigDecimal.ZERO);
        mallDaoWallet.setActivityBalance(BigDecimal.ZERO);
        mallDaoWallet.setFreezeAmount(BigDecimal.ZERO);
        mallDaoWallet.setSumIncome(BigDecimal.ZERO);
        mallDaoWallet.insert();
        redisUtil.del(RedisKeyEnum.HOME_BRAND_ISLAND.getKey());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void creationDao(CreationDaoDTO creationDaoDTO) {
        UserCreatorInfo info = userCreatorInfoDao.getById(creationDaoDTO.getId());
        if (ObjectUtil.isNull(info)) {
            throw new GlobalRunTimeException("该组织不存在");
        }
        if (info.getStatus().intValue() == 1) {
            throw new GlobalRunTimeException("该组织已经是dao了");
        }

//        if (CollUtil.isEmpty(creationDaoDTO.getList())) {
//            throw new GlobalRunTimeException("NFT凭证为空");
//        }
        UserInfo oneByUserTel = userInfoDao.getOneByUserTel(creationDaoDTO.getUserTel());
        if (BeanUtil.isEmpty(oneByUserTel)) {
            throw new GlobalRunTimeException("该主理人不存在");
        }
        // daoId.
        Long id = creationDaoDTO.getId();
        // 权益图
        String rightsInterests = creationDaoDTO.getRightsInterests();
        UserCreatorInfo userCreatorInfo = new UserCreatorInfo();
        userCreatorInfo.setUserId(oneByUserTel.getId());
        userCreatorInfo.setFalseFansSum(creationDaoDTO.getFalseFansSum());
        userCreatorInfo.setNickName(oneByUserTel.getNickName());
        userCreatorInfo.setStatus(1);
        userCreatorInfo.setRightsInterests(rightsInterests);
        userCreatorInfo.setOnlineTime(creationDaoDTO.getOnlineTime());
//        userCreatorInfo.setUserCollectionId(userApplyCreatedDaoCastellanRights.getId());
        userCreatorInfo.setId(id);
        userCreatorInfoDao.updateById(userCreatorInfo);
        // 权益卡
        List<DaoIdentityDTO> list = creationDaoDTO.getList();
        if (CollUtil.isNotEmpty(list)) {
            Map<Long, Integer> collectionCount = Maps.newHashMap();
            for (DaoIdentityDTO daoIdentityDTO : list) {
                DigitalCollection collection = digitalCollectionDao.getById(daoIdentityDTO.getCollectionId());
                collectionCount.put(collection.getId(), 1);
                Assert.notNull(collection, () -> new GlobalRunTimeException(ErrorCode.PRODUCT_NOT_FOUND));
                Assert.isTrue(collection.getUserCreatorId().longValue() == creationDaoDTO.getId().longValue(), () -> new GlobalRunTimeException("商品不属于该DAO"));
                DaoIdentity daoIdentity = new DaoIdentity();
                daoIdentity.setDaoId(creationDaoDTO.getId());
                daoIdentity.setIdentityName(daoIdentityDTO.getIdentityName());
                daoIdentity.setIdentityIcon(daoIdentityDTO.getIdentityIcon());
                daoIdentity.setLevel(daoIdentityDTO.getLevel());
                daoIdentity.setCreationContent(collection.getCreationContent());
                daoIdentity.setFirstTitle(collection.getFirstTitle());
                daoIdentity.setCollectionId(collection.getId());
                daoIdentity.setDirectPushRatio(daoIdentityDTO.getDirectPushRatio());
                daoIdentity.setEquityImage(daoIdentityDTO.getEquityImage());
                daoIdentity.insert();
            }
        }


        // 初始化DAO模板 2023年5月15日14:38:09
        mallIncomeService.add(id);

        DaoChainInfo daoChainInfo = new DaoChainInfo();
        daoChainInfo.setDaoId(userCreatorInfo.getId());
        daoChainInfo.setDaoUuid(IdUtil.getSnowflakeNextIdStr());
        Key key = metaChainHepler.userRegister();
        Assert.notNull(key, () -> new GlobalRunTimeException("dao上链失败，请稍后重试"));
        daoChainInfo.setPublicKey(key.getPublicKey());
        daoChainInfo.setAddress(key.getAddress());
        daoChainInfo.setDaoKey(key.getPrivateKey());
        daoChainInfo.setStatus(true);
        daoChainInfo.insert();
        if (ObjectUtil.isNull(daoGasDao.getByDaoId(userCreatorInfo.getId()))) {
            DaoGas daoGas = new DaoGas();
            daoGas.setDaoId(userCreatorInfo.getId());
            daoGas.setSumGas(0);
            daoGas.setLastGas(0);
            daoGas.setUsedGas(0);
            daoGas.insert();
        }

        //初始化DAO生态积分钱包
        DaoEcologyPoints daoEcologyPoints = new DaoEcologyPoints();
        daoEcologyPoints.setDaoId(userCreatorInfo.getId());
        daoEcologyPoints.setAmount(BigDecimal.ZERO);
        daoEcologyPoints.setFrozenAmount(BigDecimal.ZERO);
        daoEcologyPoints.setSumAmount(BigDecimal.ZERO);
        daoEcologyPoints.insert();
    }

    @Override
    public CreationDaoDTO findByDaoId(Long daoId) {
        UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getById(daoId);
        if (ObjectUtil.isNull(userCreatorInfo) || userCreatorInfo.getStatus().intValue() != 1) {
            throw new GlobalRunTimeException("该DAO不存在");
        }
        CreationDaoDTO creationDaoDTO = new CreationDaoDTO();
        creationDaoDTO.setId(userCreatorInfo.getId());
        UserInfo userInfo = userInfoDao.getById(userCreatorInfo.getUserId());
        creationDaoDTO.setUserTel(userInfo.getUserTel());
        creationDaoDTO.setRightsInterests(userCreatorInfo.getRightsInterests());
        creationDaoDTO.setFalseFansSum(userCreatorInfo.getFalseFansSum());
        creationDaoDTO.setOnlineTime(userCreatorInfo.getOnlineTime());
        List<DaoIdentity> daoIdentities = daoIdentityDao.getByDaoId(daoId);
        List<DaoIdentityDTO> identityDTOS = Lists.newArrayList();
        for (DaoIdentity daoIdentity : daoIdentities) {
            DaoIdentityDTO daoIdentityDTO = new DaoIdentityDTO();
            daoIdentityDTO.setIdentityName(daoIdentity.getIdentityName());
            daoIdentityDTO.setIdentityIcon(daoIdentity.getIdentityIcon());
            daoIdentityDTO.setLevel(daoIdentity.getLevel());
            daoIdentityDTO.setDirectPushRatio(daoIdentity.getDirectPushRatio());
            daoIdentityDTO.setEquityImage(daoIdentity.getEquityImage());
            daoIdentityDTO.setCreationContent(daoIdentity.getCreationContent());
            daoIdentityDTO.setFirstTitle(daoIdentity.getFirstTitle());
            daoIdentityDTO.setCollectionId(daoIdentity.getCollectionId());
            identityDTOS.add(daoIdentityDTO);
        }
        creationDaoDTO.setList(identityDTOS);
        return creationDaoDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDao(CreationDaoDTO creationDaoDTO) {
//        if (CollUtil.isEmpty(creationDaoDTO.getList())) {
//            throw new GlobalRunTimeException("NFT凭证为空");
//        }
        UserInfo oneByUserTel = userInfoDao.getOneByUserTel(creationDaoDTO.getUserTel());
        if (BeanUtil.isEmpty(oneByUserTel)) {
            throw new GlobalRunTimeException("该主理人不存在");
        }

        Long id = creationDaoDTO.getId();
        // 权益图
        String rightsInterests = creationDaoDTO.getRightsInterests();
        UserCreatorInfo userCreatorInfo = new UserCreatorInfo();
        userCreatorInfo.setUserId(oneByUserTel.getId());
        userCreatorInfo.setFalseFansSum(creationDaoDTO.getFalseFansSum());
        userCreatorInfo.setNickName(oneByUserTel.getNickName());
        userCreatorInfo.setStatus(1);
        userCreatorInfo.setRightsInterests(rightsInterests);
        userCreatorInfo.setOnlineTime(creationDaoDTO.getOnlineTime());
        userCreatorInfo.setId(id);
        userCreatorInfoDao.updateById(userCreatorInfo);
        redisUtil.del(RedisKeyEnum.HOME_BRAND_ISLAND.getKey());
        // 权益卡
        List<DaoIdentityDTO> list = creationDaoDTO.getList();

        daoIdentityDao.clearByDaoId(creationDaoDTO.getId());
        if (CollUtil.isEmpty(list)) {
            return;
        }
        Map<Long, Integer> collectionCount = Maps.newHashMap();
        for (DaoIdentityDTO daoIdentityDTO : list) {
            DigitalCollection collection = digitalCollectionDao.getById(daoIdentityDTO.getCollectionId());
            Assert.notNull(collection, () -> new GlobalRunTimeException(ErrorCode.PRODUCT_NOT_FOUND));
            Assert.isTrue(collection.getUserCreatorId().longValue() == creationDaoDTO.getId().longValue(), () -> new GlobalRunTimeException("商品不属于该DAO"));
            if (collectionCount.containsKey(collection.getId())) {
                throw new GlobalRunTimeException("同类型藏品不可添加多个");
            }
            collectionCount.put(collection.getId(), 1);
            DaoIdentity daoIdentity = new DaoIdentity();
            daoIdentity.setDaoId(creationDaoDTO.getId());
            daoIdentity.setIdentityName(daoIdentityDTO.getIdentityName());
            daoIdentity.setIdentityIcon(daoIdentityDTO.getIdentityIcon());
            daoIdentity.setLevel(daoIdentityDTO.getLevel());
            daoIdentity.setCreationContent(collection.getCreationContent());
            daoIdentity.setFirstTitle(collection.getFirstTitle());
            daoIdentity.setCollectionId(collection.getId());
            daoIdentity.setDirectPushRatio(daoIdentityDTO.getDirectPushRatio());
            daoIdentity.setEquityImage(daoIdentityDTO.getEquityImage());
            daoIdentity.insert();
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void gasReg(GasRegDTO dto) {
        DaoGas daoGas = daoGasDao.getByDaoId(dto.getId());
        if (BeanUtil.isEmpty(daoGas)) {
            throw new GlobalRunTimeException("未找到Dao的Gas信息");
        }
        daoGasDao.add(daoGas.getId(), dto.getGas());
        DaoGasDetail daoGasDetail = new DaoGasDetail();
        daoGasDetail.setDaoId(daoGas.getDaoId());
        daoGasDetail.setGasNum(dto.getGas());
        daoGasDetail.setType(1);
        daoGasDetail.setRemark("平台充值");
        daoGasDetail.insert();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBrand(UpdateBrandDTO updateBrandDTO) {
        UserCreatorInfo userCreatorInfo = new UserCreatorInfo();
        BeanUtil.copyProperties(updateBrandDTO, userCreatorInfo);
        userCreatorInfoDao.updateById(userCreatorInfo);
        redisUtil.del(RedisKeyEnum.HOME_BRAND_ISLAND.getKey());
    }

    @Override
    public AdminGetByIdVO adminGetById(Long id) {
        return userCreatorInfoDao.adminGetById(id);
    }

    /**
     * 审核状态修改
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateInfoStatus(Long id, Integer status) {
        if (id != null && status != null) {
            UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getById(id);
            if (userCreatorInfo == null) {
                throw new GlobalRunTimeException("该Dao不存在");
            }
        }
        redisUtil.del(RedisKeyEnum.HOME_BRAND_ISLAND.getKey());
        return userCreatorInfoDao.updateInfoStatus(id, status);
    }

    @Override
    public UserCreatorInfo getById(Long id) {
        return userCreatorInfoDao.getById(id);
    }

    /**
     * 根据藏品id获取他下面在售的商品
     *
     * @param id
     * @return
     */
    @Override
    public List<GetWhatHeSSellingUnderTheCollectionVO> getWhatHeSSellingUnderTheCollectionId(Long id) {
        List<GetWhatHeSSellingUnderTheCollectionVO> result = userCreatorInfoDao.getWhatHeSSellingUnderTheCollectionId(id);
        return result;
    }

    @Override
    public Page<SimpleDaoPageVO> getSimpleDaoPage(String daoName, Integer pageNo, Integer pageSize) {
        return userCreatorInfoDao.getSimpleDaoPage(daoName, pageNo, pageSize);
    }

    /**
     * 获取所有dao的简单列表(配置上线时间)
     *
     * @param daoName
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public Page<SimpleDaoPageVO> getSimpleOnlineTimeDaoPage(String daoName, Integer pageNo, Integer pageSize) {
        return userCreatorInfoDao.getSimpleOnlineTimeDaoPage(daoName, pageNo, pageSize);
    }

    @Override
    public Page<AdminSimpleDaoIdentityVO> getSimpleDaoIdentityPage(Long daoId, String collectionName, String identityName, Integer pageNo, Integer pageSize) {
        return daoIdentityDao.getSimpleDaoIdentityPage(daoId, collectionName, identityName, pageNo, pageSize);
    }

    @Override
    public Page<PageDaoEcologyPointsTransferRecordsVO> getPageDaoEcologyPointsTransferRecords(Long daoId, String toUserTel, Date startTime, Date endTime, Integer pageNo, Integer pageSize) {
        return daoEcologyPointsTransferRecordsDao.getPageDaoEcologyPointsTransferRecords(daoId, toUserTel, startTime, endTime, pageNo, pageSize);
    }

    /**
     * 获取用户所属的网体
     *
     * @param userId
     * @return
     */
    @Override
    public Long theNetworkToWhichTheUserBelongs(Long userId) {
        return userCreatorInfoDao.theNetworkToWhichTheUserBelongs(userId);
    }

    @Override
    public List<AdminUserCreatorInfoAllDao> getAllByStatus() {
        return userCreatorInfoDao.getAllByStatus();
    }

    @Override
    public Boolean updateStarRating(Long id, Long starScore) {
        UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getById(id);
        if (Objects.isNull(userCreatorInfo)) {
            throw new GlobalRunTimeException("该组织不存在");
        }
        userCreatorInfo.setStarRating(new BigDecimal(starScore).divide(new BigDecimal(20), 1, RoundingMode.HALF_UP));
        userCreatorInfo.updateById();
        return Boolean.TRUE;
    }

    @Override
    public Boolean updateEnableEcologyPool(Long id, Boolean enableEcologyPool) {
        UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getById(id);
        if (Objects.isNull(userCreatorInfo)) {
            throw new GlobalRunTimeException("该组织不存在");
        }
        if (Objects.equals(userCreatorInfo.getEnableEcologyPool(), enableEcologyPool)) {
            if (enableEcologyPool) {
                throw new GlobalRunTimeException("生态池已开启");
            }
            throw new GlobalRunTimeException("生态池已关闭");
        }
        if (enableEcologyPool && Objects.equals(userCreatorInfo.getStatus(), 0)) {
            throw new GlobalRunTimeException("该组织未创建DAO，不能开启生态池");
        }
        userCreatorInfo.setEnableEcologyPool(enableEcologyPool);
        userCreatorInfo.updateById();
        return Boolean.TRUE;
    }

    @Override
    public Boolean updateEnableJoinRank(Long id, Boolean enableJoinRank) {
        UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getById(id);
        if (Objects.isNull(userCreatorInfo)) {
            throw new GlobalRunTimeException("该Dao不存在");
        }
        if (Objects.equals(userCreatorInfo.getEnableJoinRank(), enableJoinRank)) {
            if (enableJoinRank) {
                throw new GlobalRunTimeException("是否加入排行榜已开启");
            }
            throw new GlobalRunTimeException("是否加入排行榜已关闭");
        }
        if (enableJoinRank && Objects.equals(userCreatorInfo.getStatus(), 0)) {
            throw new GlobalRunTimeException("该组织未创建DAO，不能加入排行榜");
        }
        userCreatorInfo.setEnableJoinRank(enableJoinRank);
        userCreatorInfo.updateById();
        return Boolean.TRUE;
    }

    @Override
    public List<UserCreatorInfoExcelVO> listUserCreatorByPool() {
        List<UserCreatorInfoExcelVO> list = new ArrayList<>();
        List<UserCreatorInfo> userCreatorInfos = userCreatorInfoDao.getEnableJoinRankDao();
        for (UserCreatorInfo userCreatorInfo : userCreatorInfos) {
            UserCreatorInfoExcelVO userCreatorInfoExcelVO = new UserCreatorInfoExcelVO();
            userCreatorInfoExcelVO.setId(String.valueOf(userCreatorInfo.getId()));
            userCreatorInfoExcelVO.setNickName(userCreatorInfo.getDaoName());
            list.add(userCreatorInfoExcelVO);
        }
        return list;
    }

    /**
     * 品牌手机号列表
     *
     * @param adminPhonePageDTO
     */
    @Override
    public Page<AdminUserCreatorInfoPhoneVO> findUserCreatorPhoneList(AdminPhonePageDTO adminPhonePageDTO) {
        return userCreatorInfoDao.getAdminPhonePage(adminPhonePageDTO);
    }


    /**
     * 新增Dao品牌手机号
     *
     * @param userCreatorPhoneAddDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void userCreatorAddPhone(UserCreatorPhoneAddDTO userCreatorPhoneAddDTO) {
        UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getById(userCreatorPhoneAddDTO.getDaoId());
        Assert.notNull(userCreatorInfo, () -> new GlobalRunTimeException("DAO不存在"));
        Assert.isFalse(userCreatorPhoneAddDTO.getId() == null && StringUtils.isNotBlank(userCreatorInfo.getPhoneNo()), () -> new GlobalRunTimeException("已存在"));
        userCreatorInfoDao.updateDaoPhone(userCreatorInfo.getId(), userCreatorPhoneAddDTO.getUpdateFrontTel());
        CreatorPhoneRecordDTO creatorPhoneRecordDTO = new CreatorPhoneRecordDTO();
        creatorPhoneRecordDTO.setDaoId(userCreatorInfo.getId());
        creatorPhoneRecordDTO.setDaoName(userCreatorInfo.getDaoName());
        creatorPhoneRecordDTO.setUpdateAfterTel(userCreatorPhoneAddDTO.getUpdateFrontTel());
        if (StringUtils.isNotBlank(userCreatorInfo.getPhoneNo())) {
            creatorPhoneRecordDTO.setUpdateFrontTel(userCreatorInfo.getPhoneNo());
        }
        //creatorPhoneRecordDTO.setModifyId(userCreatorPhoneAddDTO.getModifyId());
        //添加日志
        userCreatorPhoneRecordService.addUserCreatorPhoneRecord(creatorPhoneRecordDTO);

    }

    /**
     * 根据daoId 查询手机号
     *
     * @param id
     * @return
     */
    @Override
    public adminDaoPhoneVO adminPhoneById(Integer id) {
        return userCreatorInfoDao.adminPhoneById(id);
    }


    /**
     * 删除dao中手机号  赋null
     *
     * @param id
     * @return
     */
    @Override
    public void updateDaoPhoneNoStatus(Long id) {
        UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getById(id);
        Assert.notNull(userCreatorInfo, () -> new GlobalRunTimeException("dao不存在"));
        Assert.isTrue(userCreatorInfoDao.updateDaoPhoneNoStatus(id), () -> new GlobalRunTimeException("删除失败"));

    }

    /**
     * 获取用户所属的网体
     *
     * @param userId
     * @return
     */
    @Override
    public List<Long> getUserBelongingToDao(Long userId) {
        return userCreatorInfoDao.getUserBelongingToDao(userId);
    }

    /**
     * 更新
     *
     * @param id
     * @param showEcologyStatus
     * @return
     */
    @Override
    public void updateShowEcologyStatus(Long id, Boolean showEcologyStatus) {
        UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getById(id);
        if (Objects.isNull(userCreatorInfo)) {
            throw new GlobalRunTimeException("该Dao不存在");
        }
        Assert.isTrue(userCreatorInfoDao.updateShowEcologyStatus(id, showEcologyStatus), () -> new GlobalRunTimeException("修改失败"));
    }

    /**
     * 查看是否开启saas展示生态熔炼
     *
     * @param id
     * @return
     */
    @Override
    public Boolean getShowEcologyStatus(Long id) {
        UserCreatorInfo userCreatorInfo = userCreatorInfoDao.getById(id);
        if (Objects.isNull(userCreatorInfo)) {
            return Boolean.FALSE;
        }
        return userCreatorInfo.getShowEcologyStatus();
    }

    @Override
    public void updateShowPledgeStatus(Long id, Boolean showPledgeStatus) {
        Assert.notNull(userCreatorInfoDao.getById(id), () -> new GlobalRunTimeException("该Dao不存在"));
        Assert.isTrue(userCreatorInfoDao.updateShowPledgeStatus(id, showPledgeStatus), () -> new GlobalRunTimeException("修改失败"));
    }

}